<template>
  <div id="app">
    <van-config-provider
      :theme-vars="{
        // 主题色
        buttonPrimaryBackground: '#5081f8',
        buttonPrimaryBorderColor: '#5081f8',
      }"
    >
      <router-view v-slot="{ Component }" v-if="isInit">
        <keep-alive :include="['cache']">
          <component :is="Component"></component>
        </keep-alive>
      </router-view>
    </van-config-provider>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store/index'
import { showToast, showError } from 'js/utils'
import cosmo from 'cosmo-wallet-tool'

const router = useRouter()
const route = useRoute()
const store = useStore()

const isInit = ref(false) // 是否已初始化

initWallet()

// 初始化钱包
async function initWallet() {
  try {
    const isWallet = await cosmo.isWallet
    const isChrome = await cosmo.isChrome
    console.log('isWallet', isWallet)
    console.log('isChrome', isChrome)

    if (isWallet || isChrome) {
      // 在可运行的环境内
      const result = await cosmo.getPermission()
      let permission = result && result.length !== 0

      if (permission) {
        // 已授权
        getFromAddress()
      } else {
        // 未授权
        permission = await cosmo.applyPermission()

        if (permission) {
          getFromAddress()
        }
      }
    } else {
      showToast('请在Cosmo Wallet或Chrome浏览器打开')
    }
  } catch (err) {
    console.log(err)
  }
}

// 获取用户钱包地址
async function getFromAddress() {
  try {
    const fromAddress = await cosmo.getAccount()

    if (fromAddress) {
      window.fromAddress = fromAddress
      window.fromAddressHide = fromAddress.replace(
        fromAddress.slice(10, 32),
        '*******'
      )

      window.jackpotAddress = 'gx1eq92uaumtzgpr43wws4tl0kcwqwk7dzqkl5enf'
      window.jackpotAddressHide = jackpotAddress.replace(
        jackpotAddress.slice(10, 32),
        '*******'
      )
      console.log('jackpotAddress', jackpotAddress)

      // 注册
      if (route.query.superiorWalletAddress) {
        router.replace(
          `/register?superiorWalletAddress=${route.query.superiorWalletAddress}`
        )

        return setTimeout(() => {
          isInit.value = true
        }, 500)
      }

      // 未登录
      if (!store.token) {
        router.replace('/login')

        return setTimeout(() => {
          isInit.value = true
        }, 500)
      }
    } else {
      showToast('获取钱包地址失败')
    }
  } catch (err) {
    console.log(err)
  }
}
</script>

<style lang="scss">
@import 'style/index.scss';

#app {
  max-width: 400px;
  margin: 0 auto;
}
</style>
